<!--
Template Name: mixCharts
Create author: qinglong
Create Time  : 2021-01-30
-->
<template>
  <div style="height:300px; ">
    <div ref="charts"> </div>
  </div>
</template>
<script>
import { Pie } from '@antv/g2plot';
export default {
  name: 'mixCharts',
  props: {
    options: {
      type: Object,
      required: true,
    },
    chartsData: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    chartsData: {
      handler() {
        this.init();
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  methods: {
    init() {
      if (this.chart) {
        // this.chart.changeData(this.chartsData || []);
        this.chart.destroy();
        this.initChart();
      } else {
        this.$nextTick(() => {
          this.initChart();
        });
      }
    },
    initChart() {
      const el = this.$refs['charts'];
      const data = this.chartsData || [];
      let tooltipFields = [];
      if (this.chartsData[0]) {
        tooltipFields = Object.keys(this.chartsData[0]);
        tooltipFields = tooltipFields.filter((e) => e != 'value');
      }
      let options = this.options;
      const piePlot = (this.chart = new Pie(el, {
        appendPadding: 10,
        data,
        angleField: 'number',
        colorField: 'value',
        radius: 0.6,
        innerRadius: 0,
        height: 300,
        meta: {
          number: {
            alias: options.number.label,
            formatter: (v) => `${options.number.type} ${v}`,
          },
          percentage: {
            alias: options.percentage.label,
            formatter: (v) => `${v}${options.percentage.type}`,
          },
        },
        tooltip: {
          showTitle: true,
          title: 'value',
          fields: tooltipFields,
        },
        label: {
          // type: 'outer',
          type: 'spider',
          style: {
            textAlign: 'center',
          },
          autoRotate: true,
          autoHide: true,
          content: (item) => item.value,
        },
        legend: { layout: 'horizontal', position: 'bottom' },
        interactions: [{ type: 'element-active' }],
      }));
      piePlot.render();
    },
  },
};
</script>
<style lang='less' scoped>
</style>